import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
} from 'react-native';

import AndroidModule from 'src/utils/AndroidConnent'
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Constant from '../../utils/Constant'//全局变量
import StatusBarSelf from '../../components/StatusBarSelf';

import NoData from "../../utils/NoData";


let navigation
const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;

const NameColors = ['#FCBE91', '#5FE7AD', '#99C2F9', '#FFEB8E'];
const statusColors={
    '1':'#ED542E',
    '2':'#F99802',
    '3':'#2CE454',
    '4':'#2CE454',
    '5':'#ED542E',
    '6':'#999999',
    '7':'#2CE454',
    '8':'#2CE454',
}

export default class ChooseCustomersPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            keyword: '',
            customersList: [],
         
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1
        }
    }

    componentWillUnmount() {

    }

    componentDidMount() {
        this.refreshData()
    }


    render() {
        navigation = this.props.navigation
        return (
            <View style={styles.container}>
                {/* 顶部搜索 */}
                <View>
                    <StatusBarSelf />
                    <View style={styles.toplayout}>
                        <TouchableOpacity
                            style={styles.fanhuibox}
                            activeOpacity={0.8}
                            onPress={this.finish}>
                            <Image source={require('source/image/comm/back.png')} style={styles.fanhui} />
                        </TouchableOpacity>
                        <View style={styles.searchContainer}>
                        <Image source={require('source/image/electron/search.png')}  style={styles.sarchIcon} />
                            <TextInput
                                editable={true}
                                style={styles.inputbox}
                                placeholder='客户名称/手机号/意向'
                                placeholderTextColor={'#999999'}
                                maxLength={11}
                                value={this.state.keyword}
                                onChangeText={this.onChangeTextHandle}
                                onEndEditing={this.handleKeyboardFinish.bind(this)}
                            ></TextInput>
                            {
                                this.state.keyword
                                ?
                                <TouchableOpacity
                                    activeOpacity={0.8}
                                    onPress={this.clearSearch.bind(this)}>
                                <Image source={require('source/image/electron/searchClose.png')}  style={styles.sarchClose} />
                                </TouchableOpacity>
                                :
                                null
                            }
                       
                        </View>
                    </View>
                </View>
                {/* 客户数据 */}
                {this.renderList()}
            </View>
        )
    }

    finish() {
        navigation.goBack()
    }


    onChangeTextHandle = (value) => {
        this.setState({ keyword: value });
    }

    clearSearch(){
        this.setState(
            {
                keyword: ''
            }, function () {
                this.refreshData()
            });
    }

    handleKeyboardFinish(){
        this.refreshData()
    }


    renderList() {
        return (
            <View style={{ flex: 1 }}>
                <FlatList
                    data={this.state.customersList}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListHeaderComponent={this.renderHeader.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.2}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                    
                />

            </View>
        )
    }

    renderEmpty() {
        return (
            <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />

        )
    }

    renderHeader() {
        return (
            <View style={styles.header}>
            </View>
        );
    }

    renderFooter() {
        if (this.state.showFoot === 1) {
            return null;

        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    renderItemView({ item, index }) {
        return (
            <TouchableOpacity key={index}  activeOpacity={0.6}
            onPress={this.chooseItem.bind(this,item)}>
                <View style={styles.itemContainer}>
                    <View style={styles.contentContainer}>
                        <View  style={[styles.headContainer, { backgroundColor: NameColors[index % NameColors.length] }]} >
                            <Text style={styles.headName}>{this.getFirstName(item.fullname)}</Text>
                        </View>
                        <View style={styles.rightContainer}>
                            <View style={styles.rightTopContainer}>
                                <Text style={styles.name}>{item.fullname}</Text>
                                {
                                    item.grade
                                    ?
                                    <View style={styles.levelContainer}>
                                        <Text style={styles.level}>{item.grade}级</Text>
                                    </View>
                                    :
                                    null
                                }
                            
                                <Text style={[styles.status, { color: statusColors[item.lastFollowStatus] }]} >{this.getFollowText(item.lastFollowStatus)}</Text>
                            </View>
                            {
                                item.lastIntention
                                ?
                                <Text style={styles.showtitle}>{item.lastIntention}</Text>
                                :
                                null
                            }
                            {
                                item.phone
                                ?
                                <Text style={styles.showtitle}>联系电话：{item.phone}</Text>
                                :
                                null
                            }
                            {
                                item.createDate
                                ?
                                <Text style={styles.showtitle}>创建日期：{item.createDate}</Text>
                                :
                                null
                            }
                            
                            
                         
                        </View>
                    
                    </View>

                    {/* 底部的客户标签 */}
                    {
                        item.tags.length>0?
                        <View style={styles.labelContainer}>
                        {
                              item.tags.map((labelTitle, index) => { 
                                return (
                                    <View style={styles.labels}>
                                        <Text style={styles.labelcontent}>{labelTitle}</Text>
                                    </View>
                                )
                               })
                        }
                 
                    </View>
                        :
                        null
                    }
              
                </View>

            </TouchableOpacity>
        )
    }


    getFirstName(name){
        if(name){
            return name.charAt(0)
        }else{
            return '无'
        }
         
    }

    getFollowText(status){
        if(status == 1){
            return '待跟进'
        }else if(status == 2){
            return '跟进中'
        }else if(status == 3){
            return '已成交'
        }else if(status == 4){
            return '已完成'
        }else if(status == 5){
            return '已战败'
        }else if(status == 6){
            return '已失效'
        }else if(status == 7){
            return '已到店'
        }else if(status == 8){
            return '已预定'
        }else{
            return '未定义'
        }
    }

    //刷新数据
    refreshData = () => {
        this.setState({
            isRefresh: true,
            pageNo: 1,
            customersList: []
        }, function () {
            this.getCustomers()
        })
    }

    _onEndReached() {
  
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }

        //底部显示正在加载更多数据
        this.setState(
            {
                showFoot: 2,
                pageNo: this.state.pageNo + 1
            }, function () {
                this.getCustomers()
            });


    }



    getCustomers(){

        let param = {
            pageNo: this.state.pageNo,
            pageSize: 20,
            merchantId: Constant.userInfo.merchantId,
            userId: Constant.userInfo.userId,
            searchBar:this.state.keyword
        }
        HttpUtils.postRequest(HttpUrls.customerList, param)
            .then((result) => {

                let data = result.data
                if (data) {
                    let resultList = data.resultList
                 
                    if (resultList && resultList != null && resultList.length > 0) {
                        this.setState({
                            customersList: this.state.customersList.concat(resultList),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: resultList.length >= 20 ? 0 : 1,
                            })

                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });

    }

    chooseItem(item){
        let obj = {
            mobile: item.phone,
            eventName:'chooseCustomer',
            name:item.fullname
        }
        DeviceEventEmitter.emit('commonEvent', obj);
        navigation.goBack()
    }




}

const styles = StyleSheet.create({

    container: {
        flex: 1,
    },

    toplayout: {
        width: screenW,
        height: 50,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor:'#ffffff'
    },
    fanhuibox: {
        width: 40,
        height: 50,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    fanhui: {
        width: 18,
        height: 16,
    },

    searchContainer: {
        width: screenW-40-20,
        height: 34,
        backgroundColor:'#F7F8F8',
        borderRadius: 5,
        flexDirection: 'row',
        alignItems: 'center',
    },

    sarchIcon:{
        width:16,
        height:16,
        marginLeft:10,
        marginRight:10
    },

    inputbox:{
        width: screenW-40-20-36-25,
        height: 34,
        fontSize: 14,
        padding: 0, 
        margin:0,
    },
    sarchClose:{
        width:15,
        height:15,
    },


    itemContainer:{
        flexDirection: 'column',
        borderRadius: 6,
        backgroundColor:'#ffffff',
        marginLeft:15,
        marginRight:15,
        marginBottom:15,
        flex:1,
    
    },

    

    contentContainer:{
        flexDirection: 'row',
         width:'100%',
    },

    headContainer:{
        width: 54,
        height:54,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius:27,
        marginLeft:10,
        marginTop:15,
      
    },
    headName:{
        fontSize:24,
        color: '#ffffff',
        fontWeight: '600'
    },

    rightContainer:{
        marginTop:15,
        flexDirection: 'column',
        marginLeft:15,
        marginBottom:15,
        flex:1,
    },

    rightTopContainer:{
        flexDirection:'row',
        alignItems: 'center',
        flex:1,
        position:'relative'
    },

    name:{
        fontSize:16,
        color: '#333333',
        fontWeight: '500'
    },

    levelContainer:{
        width:44,
        height:18,
        backgroundColor: "rgba(237,84,46,0.1)",
        borderRadius:2,
        marginLeft:10,
        alignItems:'center',
        justifyContent:'center'
    },

    level:{
        fontSize:14,
        color: '#ED542E',
        fontWeight: '400'
    },

    status:{
        fontSize:12,
        fontWeight: '400',
        position: 'absolute',
        right:10
        
    },

    showtitle:{
        fontSize:12,
        color: '#666666',
        marginTop:6,
        fontWeight: '400'
    },

    labelContainer:{
        borderTopColor: '#E4E4E4',
        borderTopWidth: 0.5,
        flexDirection:'row',
        flexWrap: 'wrap', 
        paddingTop:10,
        flex:1,
        marginRight:10,
        marginStart: 10, marginEnd: 10
    },

    labels:{
        height:20,
        borderRadius:2,
        borderColor: '#F99802',
        borderWidth: 1,
        alignItems:'center',
        justifyContent:'center',
        marginLeft:15,
        marginBottom:10
    },

    labelcontent:{
        fontSize:12,
        color: '#F99802',
        fontWeight: '400',
        paddingTop:3,
        paddingBottom:3,
        paddingLeft:5,
        paddingRight:5
    },

    header: {
        width: '100%',
        height: 15,
    },


    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },



})